<!-- 账单实体管理 -->
<script setup lang="ts">
defineOptions({
  name: "BillEntity",
  inheritAttrs: false,
});

import {
  getBillEntityForm,
  deleteBillEntities,
  addBillEntity,
  updateBillEntity,
  listBillEntities,
  getBillEntityOptions,
} from "@/api/billEntity";
import { getBillTagOptions } from "@/api/billTag";

import {
  BillEntityForm,
  BillEntityQuery,
  BillEntityVO,
} from "@/api/billEntity/types";

import { getDictOptions } from "@/api/dict";

const queryFormRef = ref(ElForm); // 查询表单
const billEntityFormRef = ref(ElForm); // 账单实体表单

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除账单实体ID集合 用于批量删除
const queryParams = reactive<BillEntityQuery>({});

const billEntityList = ref<BillEntityVO[]>();
const billTagList = ref<OptionType[]>(); // 角色下拉数据源
const billEntityOptions = ref<OptionType[]>();

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "billEntity-form",
  width: 800,
  title: "",
});

// 账单实体表单数据
const formData = reactive<BillEntityForm>({
  status: 1,
  parentId: 0,
  sort: 1,
});

// 校验规则
const rules = reactive({
  name: [{ required: true, message: "账单实体名不能为空", trigger: "blur" }],
  type: [{ required: true, message: "账单实体类型不能为空", trigger: "blur" }],
  billTagIds: [
    { required: false, message: "账单实体Tag不能为空", trigger: "blur" },
  ],
});

/** 查询 */
async function handleQuery() {
  loading.value = true;
  await loadBillEntityOptions();
  await listBillEntities(queryParams)
    .then(({ data }) => {
      console.log(data);
      billEntityList.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 加载角色下拉数据源 */
async function loadTagOptions() {
  getBillTagOptions().then((response) => {
    billTagList.value = response.data;
  });
}

/** 获取部门下拉数据  */
async function loadBillEntityOptions() {
  getBillEntityOptions().then((response) => {
    billEntityOptions.value = [
      {
        value: 0,
        label: "顶级实体",
        children: response.data,
      },
    ];
  });
}

const dictOptions: any = ref({});
/** 加载角色下拉数据源 */
async function loadDictOptions(typeCode: string) {
  await getDictOptions(typeCode).then((response) => {
    dictOptions.value = response.data;
    console.log(response);
  });
}
/**
 * 打开弹窗
 *
 * @param type 弹窗类型  账单实体表单：billEntity-form | 账单实体导入：billEntity-import
 * @param id 账单实体ID
 */
async function openDialog(parentId?: number, id?: number) {
  dialog.visible = true;

  // 账单实体表单弹窗
  await loadTagOptions();
  await loadBillEntityOptions();
  if (id) {
    dialog.title = "修改账单实体";
    getBillEntityForm(id).then(({ data }) => {
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = "新增账单实体";
    formData.parentId = parentId ?? 0;
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  账单实体表单：billEntity-form | 账单实体导入：billEntity-import
 */
function closeDialog() {
  dialog.visible = false;
  billEntityFormRef.value.resetFields();
  billEntityFormRef.value.clearValidate();

  formData.id = undefined;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  billEntityFormRef.value.validate((valid: any) => {
    if (valid) {
      const billEntityId = formData.id;
      loading.value = true;
      if (billEntityId) {
        updateBillEntity(billEntityId, formData)
          .then(() => {
            ElMessage.success("修改账单实体成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addBillEntity(formData)
          .then(() => {
            ElMessage.success("新增账单实体成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除账单实体 */
function handleDelete(id?: number) {
  const billEntityIds = [id || removeIds.value].join(",");
  if (!billEntityIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除账单实体?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteBillEntities(billEntityIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

onMounted(async () => {
  await loadDictOptions("billEntityType");
  await handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!-- 账单实体列表 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="账单实体名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="类型" prop="types">
          <dictionary v-model="queryParams.types" type-code="billEntityType"/>
        </el-form-item> -->

        <el-form-item label="类型" prop="types">
          <el-select
            v-model="queryParams.types"
            multiple
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in dictOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上级实体" prop="parentId">
          <el-tree-select
            v-model="queryParams.parentId"
            placeholder="选择上级实体"
            :data="billEntityOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
              v-hasPerm="['sys:billEntity:add']"
              type="success"
              @click="openDialog(0, undefined)"
              ><i-ep-plus />新增</el-button
            >
            <el-button
              v-hasPerm="['sys:billEntity:delete']"
              type="danger"
              :disabled="removeIds.length === 0"
              @click="handleDelete()"
              ><i-ep-delete />删除</el-button
            >
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="billEntityList"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <!-- <el-table-column
          key="id"
          label="编号"
          align="center"
          prop="id"
          width="100"
        /> -->
        <el-table-column
          key="name"
          label="账单实体名"
          align="center"
          prop="name"
        />

        <el-table-column label="类型" align="center">
          <template #default="scope">
            <dictionary-label
              v-model="scope.row.type"
              type-code="billEntityType"
              :dictData="dictOptions"
            />
          </template>
        </el-table-column>

        <el-table-column
          key="allFromNum"
          label="流出金额"
          align="center"
          prop="allFromNum"
        />

        <el-table-column
          key="allToNum"
          label="流入金额"
          align="center"
          prop="allToNum"
        />

        <el-table-column label="余额" align="center">
          <template #default="scope">
            {{ (scope.row.allToNum - scope.row.allFromNum).toFixed(2) }}
          </template>
        </el-table-column>

        <el-table-column label="Tags" align="center" prop="tagNames">
          <template #default="scope">
            <el-tag
              v-for="(item, index) in scope.row.tagNames == null
                ? []
                : scope.row.tagNames.split(',')"
              :key="index"
              >{{ item }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
        />
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:billEntity:add']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id, undefined)"
              ><i-ep-plus />新增
            </el-button>
            <el-button
              v-hasPerm="['sys:billEntity:edit']"
              type="primary"
              link
              size="small"
              @click="openDialog(scope.row.parentId, scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['sys:billEntity:delete']"
              type="primary"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 账单实体新增/编辑表单 -->
      <el-form
        ref="billEntityFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="账单实体名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入账单实体名" />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <dictionary v-model="formData.type" type-code="billEntityType" />
        </el-form-item>
        <el-form-item label="上级实体" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级实体"
            :data="billEntityOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="Tag" prop="billTagIds">
          <el-select
            v-model="formData.billTagIds"
            multiple
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in billTagList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="实体状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
